package io.github.wanggit.antrpc.commons.bean;

import io.github.wanggit.antrpc.commons.constants.ConstantValues;
import io.github.wanggit.antrpc.commons.utils.JsonUtils;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class RegisterBean {

    private String className;

    private List<RegisterBeanMethod> methods = new ArrayList<>();

    private Integer port;

    /** 可能因为telnet暂停 */
    private boolean pause;

    public String getZookeeperFullPath(String exposeIp) {
        return getZookeeperParentFullPath(exposeIp) + "/" + className;
    }

    public String getZookeeperParentFullPath(String exposeIp) {
        return "/"
                + ConstantValues.ZK_ROOT_NODE_NAME
                + "/"
                + exposeIp
                + (null == port ? "" : ":" + port);
    }

    public byte[] getNodeData(
            String applicationName, String zkFullpath, String className, String hostInfo) {
        InterfaceNodeDataBean interfaceNodeDataBean = new InterfaceNodeDataBean();
        interfaceNodeDataBean.setFullPath(zkFullpath);
        interfaceNodeDataBean.setClassName(className);
        interfaceNodeDataBean.setHostInfo(hostInfo);
        interfaceNodeDataBean.setAppName(applicationName);
        if (!methods.isEmpty()) {
            List<String> methodStrs = new ArrayList<>(methods.size() * 2);
            Map<String, RegisterBeanMethod> methodMap = new HashMap<>();
            for (RegisterBeanMethod beanMethod : methods) {
                String key = beanMethod.toString();
                methodStrs.add(key);
                methodMap.put(key, beanMethod);
            }
            interfaceNodeDataBean.setMethods(methodStrs);
            interfaceNodeDataBean.setMethodMap(methodMap);
            interfaceNodeDataBean.setTs(System.currentTimeMillis());
        }
        return JsonUtils.toJsonBytes(interfaceNodeDataBean);
    }

    public void addMethod(RegisterBeanMethod method) {
        methods.add(method);
    }
}
